//
//  BDPerson.m
//  RuntimeDemo
//
//  Created by pxh on 16/3/7.
//  Copyright © 2016年 上海益学. All rights reserved.
//

#import "BDPerson.h"
#import <objc/runtime.h>
@interface BDPerson()<NSCoding>
@end
@implementation BDPerson
//归档
-(instancetype)initWithCoder:(NSCoder* )deconder{
    if (self = [super init]) {
        //归档存储自定义对象
        unsigned int count = 0;
        //获取指向该类所有对象的指针
        objc_property_t* properties = class_copyPropertyList([BDPerson class], &count);
        for (int i = 0 ; i < count;  i++) {
            objc_property_t property = properties[i];      //根据objc_property获取其属性的名称------>c语言字符串
            const char* name = property_getName(property);
            NSString* key = [NSString stringWithUTF8String:name];  //解码每个属性，利用kvc取出每个属性对应的数值
            [self setValue:[deconder decodeObjectForKey:key] forKey:key];
        }
 
    }
    return self;
}
//反归档
-(void)encodeWithCoder:(NSCoder *)aCoder{
    //归档存储爱定义对象
    unsigned int count = 0;
    //获取指向该类所有属性的指针
    objc_property_t* properties = class_copyPropertyList([BDPerson class], &count);
    for (int i = 0; i < count ; i ++) {
        objc_property_t property = properties[i];
        const char* name = property_getName(property);
        NSString* key = [NSString stringWithUTF8String:name];
        //编码 每个属性，利用kvc取出每个属性的对应值
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
}

@end
